package com.example.goover;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * ClassName: ConsumerDemo
 * Package: com.example.goover
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-08-05
 * Time: 19:20
 */


//消费者
public class ConsumerDemo {
    public static void main(String[] args) {

        //0.创建配置文件
        Properties properties = new Properties();

        //配置必要参数
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"hadoop102:9092");
        //反序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());

        //就算是一个消费者  消费数据也要设置消费者组id id全局唯一即可
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"hello");

        //1.创建消费者
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);

        //订阅主题 主题可能存在多个 是一个集合
        ArrayList<String> list = new ArrayList<>();
        list.add("first");
        consumer.subscribe(list);

        //消费数据
        while (true){
            //拉取数据 每秒拉取一次数据
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofSeconds(1));
            //遍历集合输出数据
            for (ConsumerRecord<String, String> stringStringConsumerRecord : poll) {
                System.out.println(stringStringConsumerRecord);
            }

        }

        //消费者没有关闭资源


    }
}
